package com.fucking.great.socket;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.socket.nio.NioClient;
import cn.hutool.socket.nio.NioServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 调研不合理，没有重连和集群机制。
 * 同时私聊需要自己封装
 */
public class SocketNioClientRecon extends  NioClient{
    Log logger = LogFactory.get();

    public SocketNioClientRecon(String host, int port) {
        this(new InetSocketAddress(host, port));
    }
    final InetSocketAddress address;
    long sleepMillis = 3000;
    public SocketNioClientRecon(InetSocketAddress address) {
        super(address);
        this.address = address;
    }

    @Override
    public NioClient write(ByteBuffer... datas) {
        NioClient write = null;
        try {
            write = super.write(datas);
        } catch (IORuntimeException e) {
            logger.info("reconnecting in {} ms , target address=[{}]",this.sleepMillis ,this.address);
            try {
                ThreadUtil.sleep(sleepMillis);
                super.init(this.address);
                super.listen();
                write = super.write(datas);
            } catch (Exception exception) {
                // 递归执行。
                write = this.write(datas);
            }


        }

        return write;
    }


}
